package com.example.teemor.es_demo.controller;

import com.example.teemor.es_demo.entity.HotProduct;
import com.example.teemor.es_demo.entity.UserProfile;
import com.example.teemor.es_demo.service.UserBehaviorService;
import com.example.teemor.es_demo.service.OrderService;
import com.example.teemor.es_demo.service.ProductService;

import jakarta.servlet.http.HttpServletRequest;

import com.example.teemor.es_demo.controller.UserController.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/analytics")
@RequiredArgsConstructor
public class AnalyticsController {

    private final UserBehaviorService userBehaviorService;
    private final OrderService orderService;
    private final ProductService productService;

    /**
     * 记录用户行为
     */
    @PostMapping("/behavior")
    public ResponseEntity<ApiResponse<Void>> recordBehavior(
            @RequestParam Long userId,
            @RequestParam String eventType,
            @RequestParam(required = false) Long productId,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String searchKeyword,
            @RequestParam(required = false) String pageUrl,
            HttpServletRequest request) {
        try {
            String sessionId = request.getSession().getId();
            userBehaviorService.recordUserBehavior(userId, sessionId, eventType, 
                    productId, category, searchKeyword, pageUrl, request);
            return ResponseEntity.ok(ApiResponse.success(null, "用户行为记录成功"));
        } catch (Exception e) {
            log.error("Failed to record user behavior", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 记录商品浏览
     */
    @PostMapping("/product-view")
    public ResponseEntity<ApiResponse<Void>> recordProductView(
            @RequestParam Long userId,
            @RequestParam Long productId,
            @RequestParam(required = false) String category,
            HttpServletRequest request) {
        try {
            String sessionId = request.getSession().getId();
            userBehaviorService.recordProductView(userId, sessionId, productId, category, request);
            return ResponseEntity.ok(ApiResponse.success(null, "商品浏览记录成功"));
        } catch (Exception e) {
            log.error("Failed to record product view", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 记录搜索行为
     */
    @PostMapping("/search")
    public ResponseEntity<ApiResponse<Void>> recordSearch(
            @RequestParam(required = false) Long userId,
            @RequestParam String searchKeyword,
            @RequestParam(required = false) String category,
            HttpServletRequest request) {
        try {
            String sessionId = request.getSession().getId();
            userBehaviorService.recordSearch(userId, sessionId, searchKeyword, category, request);
            return ResponseEntity.ok(ApiResponse.success(null, "搜索行为记录成功"));
        } catch (Exception e) {
            log.error("Failed to record search behavior", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 记录点击行为
     */
    @PostMapping("/click")
    public ResponseEntity<ApiResponse<Void>> recordClick(
            @RequestParam Long userId,
            @RequestParam Long productId,
            @RequestParam(required = false) String category,
            HttpServletRequest request) {
        try {
            String sessionId = request.getSession().getId();
            userBehaviorService.recordClick(userId, sessionId, productId, category, request);
            return ResponseEntity.ok(ApiResponse.success(null, "点击行为记录成功"));
        } catch (Exception e) {
            log.error("Failed to record click behavior", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 记录加购物车行为
     */
    @PostMapping("/add-cart")
    public ResponseEntity<ApiResponse<Void>> recordAddToCart(
            @RequestParam Long userId,
            @RequestParam Long productId,
            @RequestParam(required = false) String category,
            HttpServletRequest request) {
        try {
            String sessionId = request.getSession().getId();
            userBehaviorService.recordAddToCart(userId, sessionId, productId, category, request);
            return ResponseEntity.ok(ApiResponse.success(null, "加购物车行为记录成功"));
        } catch (Exception e) {
            log.error("Failed to record add to cart behavior", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取用户行为统计
     */
    @GetMapping("/user/{userId}/behavior-stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getUserBehaviorStats(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        try {
            Map<String, Object> stats = userBehaviorService.getUserBehaviorStats(userId, startDate, endDate);
            return ResponseEntity.ok(ApiResponse.success(stats, "获取用户行为统计成功"));
        } catch (Exception e) {
            log.error("Failed to get user behavior stats for user: {}", userId, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取用户最近行为统计
     */
    @GetMapping("/user/{userId}/recent-stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getUserRecentBehaviorStats(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "7") int days) {
        try {
            Map<String, Object> stats = userBehaviorService.getUserRecentBehaviorStats(userId, days);
            return ResponseEntity.ok(ApiResponse.success(stats, "获取用户最近行为统计成功"));
        } catch (Exception e) {
            log.error("Failed to get user recent behavior stats for user: {}", userId, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取热门商品排行
     */
    @GetMapping("/hot-products")
    public ResponseEntity<ApiResponse<List<HotProduct>>> getHotProducts(
            @RequestParam(defaultValue = "10") int limit) {
        try {
            List<HotProduct> hotProducts = userBehaviorService.getHotProducts(limit);
            return ResponseEntity.ok(ApiResponse.success(hotProducts, "获取热门商品排行成功"));
        } catch (Exception e) {
            log.error("Failed to get hot products", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取用户画像
     */
    @GetMapping("/user/{userId}/profile")
    public ResponseEntity<ApiResponse<UserProfile>> getUserProfile(@PathVariable Long userId) {
        try {
            UserProfile profile = userBehaviorService.getUserProfile(userId);
            return ResponseEntity.ok(ApiResponse.success(profile, "获取用户画像成功"));
        } catch (Exception e) {
            log.error("Failed to get user profile for user: {}", userId, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取实时PV/UV统计
     */
    @GetMapping("/realtime/pv-uv")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getRealTimePvUv() {
        try {
            Map<String, Object> stats = userBehaviorService.getRealTimePvUv();
            return ResponseEntity.ok(ApiResponse.success(stats, "获取实时PV/UV统计成功"));
        } catch (Exception e) {
            log.error("Failed to get real time PV/UV stats", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取转化率统计
     */
    @GetMapping("/conversion-rate")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getConversionRate(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        try {
            Map<String, Object> stats = userBehaviorService.getConversionRate(startDate, endDate);
            return ResponseEntity.ok(ApiResponse.success(stats, "获取转化率统计成功"));
        } catch (Exception e) {
            log.error("Failed to get conversion rate stats", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取今日行为统计
     */
    @GetMapping("/today/behavior-stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getTodayBehaviorStats() {
        try {
            Map<String, Object> stats = userBehaviorService.getTodayBehaviorStats();
            return ResponseEntity.ok(ApiResponse.success(stats, "获取今日行为统计成功"));
        } catch (Exception e) {
            log.error("Failed to get today behavior stats", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取综合分析报告
     */
    @GetMapping("/dashboard")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDashboardStats() {
        try {
            // 获取实时PV/UV
            Map<String, Object> pvUv = userBehaviorService.getRealTimePvUv();
            
            // 获取热门商品（前5名）
            List<HotProduct> hotProducts = userBehaviorService.getHotProducts(5);
            
            // 获取今日行为统计
            Map<String, Object> todayStats = userBehaviorService.getTodayBehaviorStats();
            
            // 组合数据
            Map<String, Object> dashboard = Map.of(
                    "pvUv", pvUv,
                    "hotProducts", hotProducts,
                    "todayStats", todayStats,
                    "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(ApiResponse.success(dashboard, "获取分析仪表板成功"));
        } catch (Exception e) {
            log.error("Failed to get dashboard stats", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取订单趋势
     */
    @GetMapping("/order-trend")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getOrderTrend(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) {
        try {
            List<Map<String, Object>> trend = orderService.getOrderTrend(start, end);
            return ResponseEntity.ok(ApiResponse.success(trend, "获取订单趋势成功"));
        } catch (Exception e) {
            log.error("Failed to get order trend", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取收入趋势
     */
    @GetMapping("/revenue-trend")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getRevenueTrend(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) {
        try {
            List<Map<String, Object>> trend = orderService.getRevenueTrend(start, end);
            return ResponseEntity.ok(ApiResponse.success(trend, "获取收入趋势成功"));
        } catch (Exception e) {
            log.error("Failed to get revenue trend", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取商品分类统计
     */
    @GetMapping("/category-stats")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getCategoryStats() {
        try {
            List<Object[]> rawStats = productService.countByCategory();
            List<Map<String, Object>> stats = rawStats.stream()
                .map(arr -> Map.of("category", arr[0], "value", arr[1]))
                .collect(Collectors.toList());
            return ResponseEntity.ok(ApiResponse.success(stats, "获取商品分类统计成功"));
        } catch (Exception e) {
            log.error("Failed to get category stats", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取用户行为趋势
     */
    @GetMapping("/user/{userId}/behavior-trend")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getUserBehaviorTrend(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "30") int days) {
        try {
            // 这里可以扩展实现更复杂的趋势分析
            Map<String, Object> trend = userBehaviorService.getUserRecentBehaviorStats(userId, days);
            trend.put("period", days + " days");
            trend.put("userId", userId);
            
            return ResponseEntity.ok(ApiResponse.success(trend, "获取用户行为趋势成功"));
        } catch (Exception e) {
            log.error("Failed to get user behavior trend for user: {}", userId, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
}